package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.ZtUserVip;
import org.dromara.system.domain.ZtVip;
import org.dromara.system.domain.bo.ZtUserVipBo;
import org.dromara.system.domain.vo.ZtCouponVo;
import org.dromara.system.mapper.ZtCouponMapper;
import org.dromara.system.mapper.ZtVipMapper;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.ZtUserCouponBo;
import org.dromara.system.domain.vo.ZtUserCouponVo;
import org.dromara.system.domain.ZtUserCoupon;
import org.dromara.system.mapper.ZtUserCouponMapper;
import org.dromara.system.service.IZtUserCouponService;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 用户优惠卷Service业务层处理
 *
 * @author Lion Li
 * @date 2024-06-26
 */
@RequiredArgsConstructor
@Service
public class ZtUserCouponServiceImpl implements IZtUserCouponService {

    private final ZtUserCouponMapper baseMapper;

    private final ZtCouponMapper ztCouponMapper;

    private final ZtVipMapper ztVipMapper;

    /**
     * 查询用户优惠卷
     */
    @Override
    public ZtUserCouponVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询用户优惠卷列表
     */
    @Override
    public TableDataInfo<ZtUserCouponVo> queryPageList(ZtUserCouponBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZtUserCoupon> lqw = buildQueryWrapper(bo);
        Page<ZtUserCouponVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询用户优惠卷列表
     */
    @Override
    public List<ZtUserCouponVo> queryList(ZtUserCouponBo bo) {
        LambdaQueryWrapper<ZtUserCoupon> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZtUserCoupon> buildQueryWrapper(ZtUserCouponBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZtUserCoupon> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, ZtUserCoupon::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), ZtUserCoupon::getType, bo.getType());
        lqw.like(StringUtils.isNotBlank(bo.getName()), ZtUserCoupon::getName, bo.getName());
        lqw.eq(bo.getBeginDate() != null, ZtUserCoupon::getBeginDate, bo.getBeginDate());
        lqw.eq(bo.getEndDate() != null, ZtUserCoupon::getEndDate, bo.getEndDate());
        lqw.eq(bo.getAmountOfMoney() != null, ZtUserCoupon::getAmountOfMoney, bo.getAmountOfMoney());
        lqw.eq(bo.getMinAmount() != null, ZtUserCoupon::getMinAmount, bo.getMinAmount());
        lqw.eq(StringUtils.isNotBlank(bo.getWhetherToUse()), ZtUserCoupon::getWhetherToUse, bo.getWhetherToUse());
        return lqw;
    }

    private Wrapper<ZtUserCoupon> buildQueryWrapper2(ZtUserCouponBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<ZtUserCoupon> lqw = Wrappers.query();
        lqw.eq(bo.getUserId() != null, "user_id", bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), "type", bo.getType());
        lqw.like(StringUtils.isNotBlank(bo.getName()), "name", bo.getName());
        lqw.eq(bo.getAmountOfMoney() != null, "amount_of_money", bo.getAmountOfMoney());
        lqw.like(params.get("nickName") != null,"nick_name", params.get("nickName"));
        lqw.like(params.get("phonenumber") != null,"phonenumber", params.get("phonenumber"));
        if(params.get("vipId") != null){
            ZtVip ztVip = ztVipMapper.selectById(Long.parseLong(params.get("vipId").toString()));
            Date date = new Date();
            lqw.le("min_amount",ztVip.getSpecialPrice());
            lqw.eq("whether_to_use", "0");
            lqw.le("begin_date", date);
            lqw.ge("end_date", date);
        }else{
            lqw.eq(bo.getBeginDate() != null, "begin_date", bo.getBeginDate());
            lqw.eq(bo.getEndDate() != null, "end_date", bo.getEndDate());
            lqw.eq(StringUtils.isNotBlank(bo.getWhetherToUse()), "whether_to_use", bo.getWhetherToUse());
            lqw.eq(bo.getMinAmount() != null, "min_amount", bo.getMinAmount());
        }
        return lqw;
    }

    /**
     * 新增用户优惠卷
     */
    @Override
    public Boolean insertByBo(ZtUserCouponBo bo) {
        ZtUserCoupon add = MapstructUtils.convert(bo, ZtUserCoupon.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户优惠卷
     */
    @Override
    public Boolean updateByBo(ZtUserCouponBo bo) {
        ZtUserCoupon update = MapstructUtils.convert(bo, ZtUserCoupon.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZtUserCoupon entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用户优惠卷
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<ZtUserCouponVo> queryPageList_join_user(ZtUserCouponBo bo, PageQuery pageQuery) {
        Wrapper<ZtUserCoupon> lqw = buildQueryWrapper2(bo);
        Page<ZtUserCouponVo> result = baseMapper.queryPageList_join_user(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public List<ZtUserCoupon> receive() {
        List<ZtUserCoupon> list_ZtUserCoupon = new ArrayList<ZtUserCoupon>();
        Long userId = LoginHelper.getLoginUser().getUserId();
        LocalDateTime localDateTime  = LocalDateTime.now(); // 获取当前日期
        List<ZtCouponVo> list_ztCouponVo = ztCouponMapper.selectUserUnclaimed(userId);
        for (ZtCouponVo ztCouponVo : list_ztCouponVo){
            ZtUserCoupon ztUserCoupon = new ZtUserCoupon();
            ztUserCoupon.setUserId(userId);
            ztUserCoupon.setCouponId(ztCouponVo.getId());
            ztUserCoupon.setType(ztCouponVo.getType());
            ztUserCoupon.setName(ztCouponVo.getName());
            ztUserCoupon.setBeginDate(Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()));
            LocalDateTime futureDate = localDateTime.plusDays(ztCouponVo.getClaimValidDays());//增加相应的天数
            ztUserCoupon.setEndDate(Date.from(futureDate.atZone(ZoneId.systemDefault()).toInstant()));
            ztUserCoupon.setAmountOfMoney(ztCouponVo.getAmountOfMoney());
            ztUserCoupon.setMinAmount(ztCouponVo.getMinAmount());
            ztUserCoupon.setWhetherToUse("0");
            ztUserCoupon.setRemark(ztCouponVo.getRemark());
            baseMapper.insert(ztUserCoupon);
            list_ZtUserCoupon.add(ztUserCoupon);
        }
        return list_ZtUserCoupon;
    }
}
